package com.fatdetection.demo.util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

@Component
public class QiniuUtils {
    //设置好账号的ACCESS_KEY和SECRET_KEY
    @Value("${Qiniu.ACCESS_KEY}")
    String ACCESS_KEY = "NXDCua6WT4jvgvIRXM5bEwWDmudI09CUigRSW_XY";
    @Value("${Qiniu.SECRET_KEY}")
    String SECRET_KEY = "wD705zt7IqMZNx99n6CBMhKR-dX9dJ8un-4K9XHr";
    //要上传的空间
    @Value("${Qiniu.bucketname}")
    String bucketname = "fat-oss";
    @Value("${Qiniu.baseUrl}")
    String baseUrl = "http://fat.66zx.top/";

    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    Configuration c = new Configuration(Region.region2());
    //创建上传对象
    UploadManager uploadManager = new UploadManager(c);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public boolean upload(InputStream inputStream, String fileName) throws IOException {
        try {
            Response res = uploadManager.put(inputStream, fileName, getUpToken(), null, null);
            System.out.println(res.bodyString());
            return true;
        } catch (QiniuException e) {
            return false;
        }
    }
}
